/**
 * 
 */
package com.duowan.cms.service.timetask;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.duowan.cms.common.util.DateUtil;
import com.duowan.cms.common.util.MailUtil;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.common.webapp.property.ExtendedPropertyPlaceholderConfigurer.PropertiesHolder;
import com.duowan.cms.domain.article.ArticleCount;
import com.duowan.cms.domain.article.rpst.ArticleCountRepository;
import com.duowan.cms.domain.article.rpst.ArticleRepository;
import com.duowan.cms.domain.channel.rpst.ChannelRepository;
import com.duowan.cms.domain.user.User;
import com.duowan.cms.domain.user.rpst.UserRepository;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.dto.user.UserInfo;
import com.duowan.cms.dto.user.UserSearchCriteria;
import com.duowan.cms.dto.user.UserStatus;

/**
 * 刷新定时任务:
 */
@Service("coreTimeTask")
public class CoreTimeTaskImpl implements CoreTimeTask {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private ChannelRepository channelRepository;
    
    @Autowired
    private ArticleRepository articleRepository;
    
    @Autowired
    private ArticleCountRepository articleCountRepository;

    
    @Scheduled(cron = "0 55 23 * * *")
    @Override
    public void countArticle() {
        
        Date date = new Date();
        
        List<ChannelInfo> channelList = channelRepository.getAll();
        
        for(ChannelInfo channelInfo : channelList){
            String channelId = channelInfo.getId();
            try{
                List<ArticleCount> list = articleRepository.getAllUserCount(channelId, date);
                
                for(ArticleCount articleCount : list){
                    articleCountRepository.save(articleCount);
                }
                logger.info("频道(专区)[" + channelId + "]统计处理完成!");
            }catch(Exception e){
                logger.error("频道(专区)[" + channelId + "]统计处理出错!", e);
                continue;
            }
        }
    }
    
    @Override
    public void fixCountArticle(String channelId, Date date) {
        try{
            List<ArticleCount> list = articleRepository.getAllUserCount(channelId, date);
            
            for(ArticleCount articleCount : list){
                articleCountRepository.save(articleCount);
            }
            logger.info("频道(专区)[" + channelId + "]日期[" + DateUtil.format(date, DateUtil.defaultDatePatternStr)+ "]统计处理完成!");
        }catch(Exception e){
            logger.error("频道(专区)[" + channelId + "]日期[" + DateUtil.format(date, DateUtil.defaultDatePatternStr)+ "]统计处理出错!", e);
        }
    }

    @Scheduled(cron = "0 0 3 ? * MON")
    @Override
    public void updateUserPassword() {
        
        //判断环境
        String domain = PropertiesHolder.get("domain", "http://localcms.duowan.com");
        if(!"http://cms.duowan.com".equals(domain)){
            logger.info("非生产环境["+domain+"]，不发送邮件：" + domain);
            return ;
        }
        logger.info("生产环境["+domain+"]，准备发送邮件，时间：" + DateUtil.convertDate2Str(new Date()));

        UserSearchCriteria searchCriteria = new UserSearchCriteria();
        searchCriteria.setPageSize(null);

        List<UserInfo> list = userRepository.listSearch(searchCriteria);

        for (UserInfo user : list) {
            if (user.getUserStatus() == UserStatus.NORMAL) {
                user.setPassword(StringUtil.getRandomStr(15));
                try {
                    resetUserPassword(user);
                } catch (Exception e) {
                    logger.error("用户"+user.getUserId()+"重置密码失败：", e);
                }
            }
        }
    }

    private void resetUserPassword(UserInfo userInfo) throws Exception {

        String userId = userInfo.getUserId();
        String mail = userInfo.getMail();

        if (null == mail || mail.indexOf("@") == -1) {
            throw new Exception("用户[" + userId + "]邮箱不合法");
        }

        User user = userRepository.getById(userId);
        user.update(userInfo);
        userRepository.update(user);

        // 发送mail
        String title = "发布系统(新版)重设密码通知";
        String content = userId + ",您好:<br />您的新密码为：" + userInfo.getPassword();
        MailUtil.sendHtmlEmail(mail.trim(), title, content);
        logger.info("用户"+user.getUserId()+"重置密码成功");
    }

    @Override
    public void countReply() {
        // TODO Auto-generated method stub
        
    }
}
